/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ttt.nor2.main;

import com.ttt.nor2.db.DBMysql;
import com.ttt.nor2.db.HtbBulksms;
import com.ttt.nor2.db.HtbSender;
import com.ttt.nor2.db.Smstrans;
import com.ttt.nor2.smssender.ConfigHttp;
import com.ttt.nor2.smssender.LoadClient;
import com.ttt.nor2.thread.ThPostsms;
import com.ttt.nor2.util.ChkArgs;
import com.ttt.nor2.util.ExceptionUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Properties;
import org.apache.commons.httpclient.HttpClient;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author Administrator
 */
public class MainSender {
    //user_id=9848&send_no_dis=035230420&type=20&lang=th&msgcnt=1&tel_no=0860216262&msg=test

    private static Logger logger = Logger.getLogger(MainSender.class);

    public static void main(String[] args) {
        
        ChkArgs chkargs = new ChkArgs(args);
        Properties prop = chkargs.getProps();
        PropertyConfigurator.configure(chkargs.getFileConfig());
        logger.info("Start Application sms sender...");
        // get
        String url = prop.getProperty("URL");
        String usr = prop.getProperty("USER");
        String pwd = prop.getProperty("PWD");
        String db = prop.getProperty("DBNAME");
        int sleep = Integer.parseInt(prop.getProperty("THRED_SLEEP"));
        int timeout = Integer.parseInt(prop.getProperty("TIME_OUT"));
        int thWork = Integer.parseInt(prop.getProperty("THREAD_WORK"));
        int maxConn = Integer.parseInt(prop.getProperty("MAX_CONN"));
        //connection db
        Connection conn = DBMysql.dbConn(url, usr, pwd, db);
        logger.info("Connection db sussess...");
        //String str = "1234567 -89";
        //System.out.println("["+str.substring(0, str.indexOf("-")).trim() + "]");
        //System.exit(-1);
        //load bulk
        HtbBulksms bsms = new HtbBulksms(conn);
        Hashtable htsms = bsms.loadBulk();
        //load sender
        HtbSender sender = new HtbSender(conn);
        Hashtable htSender = sender.loadSender();
        ConfigHttp conf = new ConfigHttp();
        conf.setMaxConn(maxConn);
        conf.setMaxTConn(maxConn);
        conf.setTimeout(timeout);
        //load client
        HttpClient ct = LoadClient.getClient(conf);
        while (true) {

            String sql = "select * from smstrans where status='N' order by savetime";
            try {
                PreparedStatement pstmt = conn.prepareStatement(sql);
                ResultSet rs = pstmt.executeQuery();

                while(rs.next()){
                    //check working thread
                    if (ThPostsms.getThWork() > thWork) {
                        thSleep(sleep);
                        continue;
                    }
                    Smstrans s = new Smstrans();
                    s.setTransid(rs.getString("transid"));
                    s.setAni(rs.getString("ani"));
                    s.setBulkid(htsms, rs.getInt("bulkid"));
                    s.setLang(rs.getString("lang"));
                    s.setMsgout(rs.getString("msgout"));
                    s.setSender(htSender, rs.getInt("sender"));
                    s.setType(rs.getString("type"));
                    s.setConn(conn);
                    s.setLockRec();
                    //run thread
                    ThPostsms post = new ThPostsms(s, ct);
                    post.run();
                }// end loop query smstrans
                rs.close();
                pstmt.close();
                rs = null;
                pstmt = null;

            } catch (Exception e) {
                logger.error("Query load smstrans error! " + ExceptionUtil.getStackTrace(e));
                try {
                    conn.close();
                } catch (SQLException ex) {
                    logger.error("Close db error! " + ExceptionUtil.getStackTrace(ex));
                }
            }//end try query smstrans
            //clean mem
            System.gc();
            // thread sleep
            thSleep(sleep);

        }//end loop while never die


    }// end main

    private static void thSleep(int sleep) {
        try {
            Thread.sleep(sleep);
            logger.debug("Thread sleep [" + sleep + "]");
        } catch (Exception e) {
            logger.error("Exception Thread sleep " + ExceptionUtil.getStackTrace(e));
        }
    }
}
